<?php

namespace app\common\logic;

use app\common\model\trSystemSet;
use app\common\util\Tools;
use think\facade\Env;

/**
 * @package Common\Logic
 * 通用的逻辑处理
 */
class CommonLogic
{
    // 获取省市区数据存储到本地
    public static function savePCA()
    {
        $list = Tools::curl("https://apis.map.qq.com/ws/district/v1/list?key=HL6BZ-D24K4-BAXU3-DDKRU-WKF5Z-XCFJ5");
        $list = @json_decode($list,true);
        $provinceList = [];
        if(isset($list["result"][0])) {
            foreach ($list["result"][0] as $p => $provinceItem) {
                $cityTemp = array_slice($list["result"][1], $provinceItem["cidx"][0], $provinceItem["cidx"][1] - $provinceItem["cidx"][0]+1);
                $cityList = [];
                foreach ($cityTemp as $k => $cityItem) {
                    $cityList[$k]["code"] = $cityItem["id"];
                    $cityList[$k]["name"] = $cityItem["fullname"];
                    $cityList[$k]["simpleName"] = $cityItem["name"];
                    if(isset($cityItem["cidx"])){
                        $areaTemp = array_slice($list["result"][2], $cityItem["cidx"][0], $cityItem["cidx"][1] - $cityItem["cidx"][0]+1);
                        $areaList = [];
                        foreach ($areaTemp as $ks => $v){
                            $areaList[$ks]["code"] = $v["id"];
                            $areaList[$ks]["name"] = $v["fullname"];
                            $areaList[$ks]["simpleName"] = isset($v["name"]) ? $v["name"] : null;
                        }
                        $cityList[$k]["children"] = $areaList;
                    }
                }
                $provinceList[$p]["code"] = $provinceItem["id"];
                $provinceList[$p]["name"] = $provinceItem["fullname"];
                $provinceList[$p]["simpleName"] = $provinceItem["name"];
                $provinceList[$p]["children"] = $cityList;
            }
        }
        file_put_contents(Env::get("extend_path") . "/pca-code.json", json_encode($provinceList, JSON_UNESCAPED_UNICODE));
        return $provinceList;
    }

    /**
     * @param $url
     * @param $params
     * @return string
     * 地址加上参数
     */
    public static function urlAppend($url, $params){
        if(empty($url)){
            return $url;
        }
        if(is_array($params)){
            $pairs = array();
            foreach ($params as $k => $v){
                $pairs[] = "$k=".urlencode($v);
            }
            $params = implode('&', $pairs);
        }
        if(strpos($url, "?") !== false) {
            $url .= "&{$params}";
        }else {
            $url .= "?{$params}";
        }
        return $url;
    }

    /**
     * @param $tablePrefix
     * @param $tableData
     * @return mixed|string|string[]|null
     * 正则表达式替换数据库表成PHP数组
     */
    public static function replaceTable($tablePrefix, $tableData){
        preg_match_all("/\s\`({$tablePrefix}\w+)\`/", $tableData, $res);
        $string = var_export(array_unique($res[1]),true);
        $string = preg_replace("/\w*(\d+\s=>\s)/", "", $string);
        return $string;
    }

    /**
     * @param string $fileName  文件名
     * @param array $arrHeader  第一行的内容，标题
     * @param array $arrWidth   每列的宽度
     * @param array $arrKey     每列数据对应的key
     * @param array $arrData    每列的数据数组
     * @return array|bool
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * 数据excel导出
     */
    public static function exportExcel($fileName, $arrHeader, $arrWidth, $arrKey, $arrData){
        require_once Env::get("extend_path") . "/phpExcel/PHPExcel.php";
        $objPHPExcel = new \PHPExcel();
        $excel = $objPHPExcel->setActiveSheetIndex(0);
        $key = 65;
        $time = 0;
        foreach ($arrHeader as $k => $value) {
            if($key + $time < 91){
                $mark = chr($key + $time);
            }else{
                $temp = floor($time / 26);
                $mark = chr($key + $temp - 1) . chr($key + $time - (26 * $temp));
            }
            $time++;
            $excel->setCellValue($mark . '1', $value);
            if(isset($arrWidth[$k]))
                $excel->getColumnDimension($mark)->setWidth($arrWidth[$k]);
        }
        // 设置第一行的内容文字加粗
        $excel->getStyle(chr($key) . '1:' . chr($key + count($arrHeader)) . '1')->getFont()->setBold(true);
        foreach ($arrData as $i => $item) {
            $time = 0;
            foreach ($arrKey as $file) {
                if($key + $time < 91){
                    $mark = chr($key + $time);
                }else{
                    $temp = floor($time / 26);
                    $mark = chr($key + $temp - 1) . chr($key + $time - (26 * $temp));
                }
                $time++;
                $excel->setCellValue($mark . ($i + 2), $item[$file]);
            }
        }
        $excel->setTitle($fileName);
        $fileName = "{$fileName}.xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$fileName.'"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        if(request()->server("IS_SCF")) {
            $objWriter->save('/tmp/'.$fileName);
            return [
                "header" => ["Content-type" => "application/octet-stream", "Content-Disposition" => "attachment; filename=" . $fileName, 'Accept-Ranges' => 'bytes'],
                "content" => file_get_contents('/tmp/'.$fileName)
            ];
        }else {
            $objWriter->save('php://output');
            return true;
        }
    }

    /**
     * @param int $time
     * @return false|string
     * 时间戳转为文字说明
     */
    public static function handleTimeToText($time){
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        if($beginToday <= $time){ // 今天内
            if(($difference = floor((time() - $time) / 3600)) > 0){
                return "{$difference}小时前";
            }else{
                $difference = floor((time() - $time) / 60);
                return $difference > 0 ? "{$difference}分钟前" : "刚刚";
            }
        }elseif($beginToday - $time <= 86400){ // 昨天
            return "昨天";
        }elseif($beginToday - $time <= 86400 * 2){ // 前天
            return "前天";
        }elseif(mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")) <= $time){ // 本周
            return "本周";
        }else{
            return date("Y-m-d", $time);
        }
    }

    public static function getAddress($latitude, $longitude){
        $key = trSystemSet::getValue("MapSetting");
        if(empty($key)){
            $key = ["TCMapKey" => "FMRBZ-2REKF-5VJJM-NW664-LTAK6-SMBEI"];
        }
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?key={$key["TCMapKey"]}";
        $res = json_decode(Tools::curl($url."&location={$latitude},{$longitude}"), true);
        if(!isset($res["result"]["address"])){
            return false;
        }
        return $res["result"]["address"];
    }

    public static function getLatLon($address){
        $key = trSystemSet::getValue("MapSetting");
        if(empty($key)){
            $key = ["TCMapKey" => "FMRBZ-2REKF-5VJJM-NW664-LTAK6-SMBEI"];
        }
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key={$key["TCMapKey"]}";
        $res = json_decode(Tools::curl($url), true);
        if(!isset($res["result"]["location"])){
            return false;
        }
        return $res["result"]["location"];
    }
}